package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MsgDomain;
import com.sendpo.zjx.sendpo.domain.SearchDesginDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.KeyBoardUtils;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 朱俊鑫 on 2018
 */

public class PrivateSpeechiActivity extends AppCompatActivity implements SpeechSynthesizerListener {
    // ================选择TtsMode.ONLINE  不需要设置以下参数; 选择TtsMode.MIX 需要设置下面2个离线资源文件的路径
    private static final String TEMP_DIR = "/sdcard/baiduTTS"; // 重要！请手动将assets目录下的3个dat 文件复制到该目录

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.switch_bt)
    RelativeLayout switchBt;
    @BindView(R.id.send_rl)
    RelativeLayout sendRl;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.im_list)
    RecyclerView imList;
    SpeechSynthesizer mSpeechSynthesizer;
    public Adpater adpater;
    public LinearLayoutManager linearLayoutManager;
    @BindView(R.id.sendbt)
    Button sendbt;
    public boolean isSwitch = false;
    @BindView(R.id.dingzhi_alldin_bt)
    RelativeLayout dingzhiAlldinBt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_privatespeech);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();

    }

    private void initComponent() {
        mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        mSpeechSynthesizer.setSpeechSynthesizerListener(this); //listener是
        mSpeechSynthesizer.setContext(this);
        mSpeechSynthesizer.setAppId(HttpUrl.Baidu_APPID);
        mSpeechSynthesizer.setApiKey(HttpUrl.Baidu_APPKEY, HttpUrl.Baidu_SECRETKEY);
        // 5. 以下setParam 参数选填。不填写则默认值生效
        // 设置在线发声音人： 0 普通女声（默认） 1 普通男声 2 特别男声 3 情感男声<度逍遥> 4 情感儿童声<度丫丫>
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置合成的音量，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME, "9");
        // 设置合成的语速，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED, "5");
        // 设置合成的语调，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_PITCH, "5");
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
        mSpeechSynthesizer.initTts(TtsMode.MIX);
        linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        imList.setLayoutManager(linearLayoutManager);
        imList.setAdapter(adpater = new Adpater(this));
        if (adpater != null) {
            adpater.img_text(0, "您好，你的智能助理小送为你服务", mSpeechSynthesizer);
        }
    }

    @OnClick(value = {R.id.backbt, R.id.sendbt, R.id.switch_bt,R.id.dingzhi_alldin_bt})
    public void onMuClick(View view) {
        switch (view.getId()) {
            case R.id.dingzhi_alldin_bt:
                   List<User>  userList=Xutils.queryAll(getApplication(),User.class);
                    if(userList==null||userList.size()==0){
                   Tools.redirectActivity(this,LoginActivity.class);
                        return;
                    }
                Tools.redirectActivity(this,PrivateAllDindanListActivity.class);
                break;
            case R.id.backbt:
                finish();
                break;
            case R.id.sendbt:
                if (TextUtils.isEmpty(contentEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (adpater != null) {
                    adpater.img_text(1, contentEdit.getText().toString().trim(), mSpeechSynthesizer);
                }
                contentEdit.getText().clear();
                KeyBoardUtils.closeKeybord(contentEdit, this);
                break;

            case R.id.switch_bt:
                if (isSwitch) {

                } else {

                }
                break;
        }
    }


    @Override
    public void onSynthesizeStart(String s) {
        System.out.println("**************************onSynthesizeStart*" + s);
    }

    @Override
    public void onSynthesizeDataArrived(String s, byte[] bytes, int i) {

    }

    @Override
    public void onSynthesizeFinish(String s) {
        System.out.println("**************************onSynthesizeFinish*" + s);
    }

    @Override
    public void onSpeechStart(String s) {

    }

    @Override
    public void onSpeechProgressChanged(String s, int i) {

    }

    @Override
    public void onSpeechFinish(String s) {

    }

    @Override
    public void onError(String s, SpeechError speechError) {
        System.out.println("*********************************" + speechError.description + speechError.code);
    }


    public class Adpater extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MsgDomain> databeen = new ArrayList<>();
        public LayoutInflater inflater;

        public Adpater(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 0) {
                return new IMIndexHolder(inflater.inflate(R.layout.layout_im_msg_text, parent, false));
            } else if (viewType == 1) {
                return new UserIndexHolder(inflater.inflate(R.layout.layout_im_user_msg_text, parent, false));
            }

            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            MsgDomain msg = databeen.get(position);
            IMIndexHolder imIndexHolder;
            UserIndexHolder userIndexHolder;
            if (getItemViewType(position) == 0) {
                imIndexHolder = (IMIndexHolder) holder;
                if (msg.message_type == 0) {
                    imIndexHolder.im_ll.removeAllViews();
                    imIndexHolder.im_ll.setVisibility(View.GONE);
                    imIndexHolder.im_msg.setVisibility(View.VISIBLE);
                    imIndexHolder.im_msg.setText(msg.message_user_message);
                } else if (msg.message_type == 1) {
                    imIndexHolder.im_ll.removeAllViews();
                    imIndexHolder.im_ll.setVisibility(View.VISIBLE);
                    imIndexHolder.im_msg.setVisibility(View.GONE);

                    List<SearchDesginDomain.DataBean> dataBeans = msg.dataBeans;
                    System.out.println("**************************dataBeans:size" + dataBeans.size());
                    for (int i = 0; i < dataBeans.size(); i++) {
                        final SearchDesginDomain.DataBean dataBean = dataBeans.get(i);
                        View view = View.inflate(PrivateSpeechiActivity.this, R.layout.layout_index_sendpoitem, null);
                        ImageView indeximg = view.findViewById(R.id.img);
                        TextView realmoney = view.findViewById(R.id.realmoney);
                        TextView originmoney = view.findViewById(R.id.originmoney);
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");
                        realmoney.setText("¥" + decimalFormat.format(Double.parseDouble(dataBean.getPrice() + "")));
                        originmoney.setVisibility(View.GONE);
                        TextView name = view.findViewById(R.id.name);
                        Glide.with(PrivateSpeechiActivity.this).load(dataBean.getImg() + "")
                                .crossFade(1000)
                                .centerCrop()
                                .into(indeximg);
                        name.setText("" + dataBean.getTitle());
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("id", dataBean.getId());
                                Tools.redirectActivity(PrivateSpeechiActivity.this, PrivateGenicInfoActivity.class, map);
                            }
                        });
                        imIndexHolder.im_ll.addView(view);
                    }
                }

            } else if (getItemViewType(position) == 1) {
                userIndexHolder = (UserIndexHolder) holder;
                System.out.println("****************************message_user_message:" + msg.message_user_message);
                userIndexHolder.user_msg.setText(msg.message_user_message);
            }


        }

        @Override
        public int getItemViewType(int position) {
            MsgDomain domain = databeen.get(position);
            return domain.message_user_type;
        }

        @Override
        public int getItemCount() {
            return databeen.size();
        }

        public class IMIndexHolder extends RecyclerView.ViewHolder {
            public TextView im_msg;
            public LinearLayout im_ll;

            public IMIndexHolder(View itemView) {
                super(itemView);
                im_msg = itemView.findViewById(R.id.im_msg);
                im_ll = itemView.findViewById(R.id.im_ll);
            }
        }

        public class UserIndexHolder extends RecyclerView.ViewHolder {
            public TextView user_msg;

            public UserIndexHolder(View itemView) {
                super(itemView);
                user_msg = itemView.findViewById(R.id.user_msg);
            }
        }

        public void addMessage(MsgDomain msgDomain) {
            databeen.add(msgDomain);
            notifyDataSetChanged();
            if (imList != null && databeen.size() != 0) {
                imList.smoothScrollToPosition(databeen.size() - 1);
            }
        }

        //IM语音自动说话，文本
        public void img_text(final int userType, final String message, final SpeechSynthesizer synthesizer) {

            System.out.println("*********************message" + message);
            if (userType == 0) {
                final MsgDomain msgDomain = new MsgDomain();
                synthesizer.speak(message);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        PrivateSpeechiActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                msgDomain.message_user_type = userType;
                                msgDomain.message_type = 0;
                                msgDomain.message_user_message = message;
                                addMessage(msgDomain);
                            }
                        });

                    }
                }).start();

            } else if (userType == 1) {
                final MsgDomain msgDomain = new MsgDomain();
                msgDomain.message_user_type = userType;
                msgDomain.message_type = 0;
                msgDomain.message_user_message = message;
                addMessage(msgDomain);
                Map<String, String> map = new HashMap<>();
                map.put("str", "" + message);

                Xutils.GET(HttpUrl.searchDesign, map, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Gson gson = new Gson();
                        SearchDesginDomain desginDomain = gson.fromJson(result, SearchDesginDomain.class);
                        if (desginDomain.isFlag()) {
                            img_text(0, desginDomain.getMsg() + "", synthesizer);
                            haveDomain(desginDomain, synthesizer);

                        } else {
                            img_text(0, desginDomain.getMsg() + "", synthesizer);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }


        }

        public void haveDomain(final SearchDesginDomain desginDomain, final SpeechSynthesizer synthesizer) {
            final MsgDomain msgDomain = new MsgDomain();
//       synthesizer.speak(desginDomain.getMsg());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    PrivateSpeechiActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            msgDomain.message_user_type = 0;
                            msgDomain.message_type = 1;
                            msgDomain.message_user_message = desginDomain.getMsg();
                            msgDomain.dataBeans = desginDomain.getData();
                            addMessage(msgDomain);
                        }
                    });

                }
            }).start();
        }

    }
}
